#include "preHeader.h"
#include "TransMgr.h"

TransMgr::TransMgr()
{
}

TransMgr::~TransMgr()
{
}

void TransMgr::RunGC()
{
	while (!m_recycleBin.empty()) {
		auto& pair = m_recycleBin.front();
		if (pair.second < GET_UNIX_TIME) {
			m_recycleBin.pop();
		} else {
			break;
		}
	}
}

void TransMgr::AddClient(ClientSession* pSession)
{
	std::lock_guard<std::shared_mutex> lock(m_clientMutex);
	m_clientMap.emplace(pSession->sn(), pSession);
}

void TransMgr::RemoveClient(ClientSession* pSession)
{
	std::lock_guard<std::shared_mutex> lock(m_clientMutex);
	if (m_clientMap.erase(pSession->sn()) != 0) {
		m_recycleBin.emplace(
			pSession->GetConnection(), GET_UNIX_TIME + GC_DELAY_TIME);
	}
}

ClientSession* TransMgr::GetClient(uint32 sn)
{
	std::shared_lock<std::shared_mutex> lock(m_clientMutex);
	auto itr = m_clientMap.find(sn);
	return itr != m_clientMap.end() ? itr->second : NULL;
}

void TransMgr::AddMapServer(MapServerSession* pSession)
{
	std::lock_guard<std::shared_mutex> lock(m_mapServerMutex);
	m_mapServerMap.emplace(pSession->GetMSSN(), pSession);
}

void TransMgr::RemoveMapServer(MapServerSession* pSession)
{
	std::lock_guard<std::shared_mutex> lock(m_mapServerMutex);
	if (m_mapServerMap.erase(pSession->GetMSSN()) != 0) {
		m_recycleBin.emplace(
			pSession->GetConnection(), GET_UNIX_TIME + GC_DELAY_TIME);
	}
}

MapServerSession* TransMgr::GetMapServer(uint32 msSN)
{
	std::shared_lock<std::shared_mutex> lock(m_mapServerMutex);
	auto itr = m_mapServerMap.find(msSN);
	return itr != m_mapServerMap.end() ? itr->second : NULL;
}
